package com.aprivate.kn.ratingsystem.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SearchView;
import android.widget.TextView;

import com.aprivate.kn.ratingsystem.R;
import com.aprivate.kn.ratingsystem.adapter.CommonAdapter;
import com.aprivate.kn.ratingsystem.adapter.CommonViewHolder;
import com.aprivate.kn.ratingsystem.bean.DataOfProductList;
import com.aprivate.kn.ratingsystem.bean.ProjectInfo;
import com.aprivate.kn.ratingsystem.bean.ProjectUsersBean;
import com.aprivate.kn.ratingsystem.bean.ResponseBean;
import com.aprivate.kn.ratingsystem.config;
import com.aprivate.kn.ratingsystem.daoBean.Answer;
import com.aprivate.kn.ratingsystem.daoBean.Elements;
import com.aprivate.kn.ratingsystem.daoBean.ProductInfo;
import com.aprivate.kn.ratingsystem.daoBean.Project;
import com.aprivate.kn.ratingsystem.daoBean.Topics;
import com.aprivate.kn.ratingsystem.daoBean.User;
import com.aprivate.kn.ratingsystem.daoutil.AnswerDaoUtil;
import com.aprivate.kn.ratingsystem.daoutil.ElementDaoUtil;
import com.aprivate.kn.ratingsystem.daoutil.ProductInfoDaoUtil;
import com.aprivate.kn.ratingsystem.daoutil.ProjectDaoUtil;
import com.aprivate.kn.ratingsystem.daoutil.ProjectUserDaoUtil;
import com.aprivate.kn.ratingsystem.daoutil.TopicsDaoUtil;
import com.aprivate.kn.ratingsystem.daoutil.UserDaoUtil;
import com.aprivate.kn.ratingsystem.util.GsonUtils;
import com.aprivate.kn.ratingsystem.util.NetworkUtils;
import com.aprivate.kn.ratingsystem.util.ProjectUtilsKt;
import com.aprivate.kn.ratingsystem.viewUtil.ToastUtil;
import com.example.okhttputils.CallBackUtil;
import com.example.okhttputils.OkhttpUtil;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by kenan on 2018/10/31.
 */

public class ProjectListActivity extends Activity implements EasyPermissions.PermissionCallbacks {
    private Button exitButton;
    private TextView mAccountNum;
    private RefreshLayout listViewCustom;
    private ListView mListView;
    List<DataOfProductList.ProductInfoBean> mProjectBeans;
    private CommonAdapter<DataOfProductList.ProductInfoBean> productInfoBeanCommonAdapter;
    private int mPageNum = 0;
    private int mPageSize = 10;
    private boolean isLastPage = false;
    private ProjectDaoUtil projectDaoUtil;
    private ProductInfoDaoUtil productInfoDaoUtil;
    private TopicsDaoUtil topicsDaoUtil;
    private ElementDaoUtil elementDaoUtil;
    private AnswerDaoUtil answerDaoUtil;
    private ProjectUserDaoUtil projectUserDaoUtil;
    private Gson gson;
    private SearchView mSearchView;
    private String mSearchString = "";
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    private ProgressBar mProgressBar;

    /**
     * 0 - 第一次获取数据
     * 1 - 下拉刷新
     * 2 - 上拉加载 翻页
     */
    private InputMethodManager inputMethodManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_projectlist);
        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        answerDaoUtil = new AnswerDaoUtil(this);
        elementDaoUtil = new ElementDaoUtil(ProjectListActivity.this);
        projectUserDaoUtil = ProjectUserDaoUtil.getInstance();
        mAccountNum = findViewById(R.id.tv_account_num);
        exitButton = findViewById(R.id.bt_exit);
        listViewCustom = findViewById(R.id.lv_projectlist);
        mListView = findViewById(R.id.list_view);
        mSearchView = findViewById(R.id.sv_SearchView);
        mProgressBar = findViewById(R.id.progress);
        mProjectBeans = new ArrayList<>();
        gson = new Gson();
        productInfoBeanCommonAdapter = new CommonAdapter<DataOfProductList.ProductInfoBean>(this, mProjectBeans, R.layout.view_projectlist_item) {
            @Override
            public void convert(CommonViewHolder holder, DataOfProductList.ProductInfoBean productInfoBean) {
                pushView(holder, productInfoBean);

            }
        };
        //设置显示账号信息
        User user = UserDaoUtil.getInstance().getUser();
        if (null != user && !TextUtils.isEmpty(user.getUserName())) {
            mAccountNum.setText("当前用户：" + user.getUserName());
        } else {
            mAccountNum.setVisibility(View.GONE);
        }

        mListView.setAdapter(productInfoBeanCommonAdapter);
        setListViewCustomListener();
        listViewCustom.autoRefresh();
        initListener();

    }

    private void initListener() {
        exitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doLogout();
            }
        });
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                mPageNum = 0;
                mSearchString = query;
                listViewCustom.autoRefresh();
                inputMethodManager.hideSoftInputFromWindow(mSearchView.getWindowToken(), 0); //强制隐藏键盘
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                mPageNum = 0;
                mSearchString = newText;
                listViewCustom.autoRefresh();
                return true;
            }
        });
    }

    private void doLogout() {
        UserDaoUtil.getInstance().deleteUser(UserDaoUtil.getInstance().getUser());
        finish();
        startActivity(new Intent(this, LoginActivity.class));
    }

    private void setListViewCustomListener() {
        listViewCustom.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPageNum = 0;
                refreshLayout.setNoMoreData(false);
                getDataFromServiceOrDataBase(mSearchString);
            }
        });
        listViewCustom.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLastPage) {
                    ToastUtil.showShortToast(ProjectListActivity.this, "我也是有底线的/(ㄒoㄒ)/~~");
                    listViewCustom.finishLoadMoreWithNoMoreData();
                } else {
                    mPageNum++;
                    getDataFromServiceOrDataBase("");
                }
            }
        });
    }

    private void pushView(CommonViewHolder holder, final DataOfProductList.ProductInfoBean productInfoBean) {
        if (null != productInfoBean) {
            if (productInfoBean.isFirstProject()) {
                //显示表头，隐藏按钮
                holder.setText(R.id.tv_num, "序号");
                holder.setText(R.id.tv_projectName, "项目名称");
                holder.setText(R.id.tv_projectStatus, "项目状态");
                holder.setText(R.id.tv_create_time, "创建时间");
                holder.setText(R.id.tv_creater, "创建者");
                holder.getView(R.id.bt_download).setVisibility(View.INVISIBLE);
                holder.getView(R.id.bt_productionInfo).setVisibility(View.INVISIBLE);
                holder.getView(R.id.bt_rating).setVisibility(View.INVISIBLE);
                holder.getView(R.id.bt_up).setVisibility(View.INVISIBLE);
            } else {
                holder.setText(R.id.tv_num, "" + holder.getPosition());
                holder.setText(R.id.tv_projectName, productInfoBean.getName());
                holder.setText(R.id.tv_projectStatus, ProjectUtilsKt.getStatusName(productInfoBean.getStatus()));
                holder.setText(R.id.tv_creater, TextUtils.isEmpty(productInfoBean.getCreator()) ? "" : productInfoBean.getCreator());
                String createTime = "";
                try {
                    createTime = format.format(new Date(productInfoBean.getCreateTime()));
                } catch (Exception e) {

                }
                holder.setText(R.id.tv_create_time, createTime);
                Button button_download = holder.getView(R.id.bt_download);
                Button button_productionInfo = holder.getView(R.id.bt_productionInfo);
                Button button_rating = holder.getView(R.id.bt_rating);
                Button button_up = holder.getView(R.id.bt_up);
                button_download.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        downloadRatingInfo(productInfoBean.getId() + "",true);
                    }
                });
                button_rating.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        List<Elements> elements = elementDaoUtil.queryElmentsByQueryBuilder(productInfoBean.getId() + "");
                        if (elements == null || elements.isEmpty()) {
                            ToastUtil.showLongToast(ProjectListActivity.this, "请先下载评级数据！");
                            return;
                        }
                        Intent intent = new Intent(ProjectListActivity.this, RatingActivity.class);
                        intent.putExtra("productionid", productInfoBean.getId() + "");
                        ProjectListActivity.this.startActivity(intent);
                    }
                });
                button_up.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        uploadAll(productInfoBean);
                    }
                });
                button_productionInfo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ProjectInfoActivity.start(ProjectListActivity.this, productInfoBean);
                    }
                });
            }
        }
    }

    private void downloadRatingInfo(final String projectId, final boolean showToast) {
        mProgressBar.setVisibility(View.VISIBLE);
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("projectId", projectId);
        OkhttpUtil.okHttpPost(config.URL + config.ProjectInfo_Url, paramsMap, config.getHeaderMap(), new CallBackUtil.CallBackString() {
            @Override
            public void onFailure(Call call, Exception e) {
                mProgressBar.setVisibility(View.GONE);
            }

            @Override
            public void onResponse(String response) {
                mProgressBar.setVisibility(View.GONE);
                Gson gson = new Gson();
                ProjectInfo projectInfo = GsonUtils.jsonToBean(response, ProjectInfo.class);
                if (projectInfo.statusCode == 200) {
                    String dataStr = gson.toJson(projectInfo.data);
                    try {
                        JSONObject dataJObj = new JSONObject(dataStr);
                        ProductInfo productInfo = GsonUtils.jsonToBean(projectInfo.data.productInfo, ProductInfo.class);
                        JSONArray elementsJsonArry = dataJObj.getJSONArray("elements");
                        JSONArray topicsJsonArray = dataJObj.getJSONArray("topics");
                        JSONArray projectUsersJsonArray = dataJObj.getJSONArray("projectUsers");
                        // 数据项目信息入库
                        productInfoDaoUtil = new ProductInfoDaoUtil(ProjectListActivity.this);
                        topicsDaoUtil = new TopicsDaoUtil(ProjectListActivity.this);
                        setProductRatingInfoOfDao(productInfo.getId() + "", projectUsersJsonArray, elementsJsonArry, topicsJsonArray, gson);
                        productInfoDaoUtil.insertProductInfo(productInfo);
                        topicsDaoUtil.insertListTopics(topicsList);
                        elementDaoUtil.insertListElement(elementsList);
                        projectUserDaoUtil.insertListProject(projectUserList);
                        if (showToast)
                            ToastUtil.showLongToast(ProjectListActivity.this, "下载成功");
                    } catch (JSONException e) {
                        e.printStackTrace();
                        mProgressBar.setVisibility(View.GONE);
                    }
                }

            }
        });

    }

    // 下载项目评级信息
    private void getDataFromServiceOrDataBase(String searchString) {
        if (!NetworkUtils.isNetworkAvailable(this) && mPageNum == 0) {
            mPageNum = 0;
            ToastUtil.showShortToast(this, "当前网络异常，数据为离线数据");
            if (!TextUtils.isEmpty(mSearchString)) {
                //数据库搜索
                searchDataFromDB();
                return;
            }
            loadDataFromDB();
            return;
        }
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("pageIndex", String.valueOf(mPageNum));
        paramsMap.put("pageSize", String.valueOf(mPageSize));
        paramsMap.put("name", searchString);
        paramsMap.put("unitName", "");
        OkhttpUtil.okHttpPost(config.URL + config.ProjectList_Url, paramsMap, config.getHeaderMap(), new CallBackUtil.CallBackString() {

            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                ResponseBean responseBean = gson.fromJson(response, ResponseBean.class);
                if (responseBean.getStatusCode().equals("200")) {
                    if (mPageNum == 0) {
                        mProjectBeans.clear();

                    }
                    try {
                        DataOfProductList dataOfProductList = gson.fromJson(gson.toJson(responseBean.getData()), DataOfProductList.class);
                        if (null != dataOfProductList && null != dataOfProductList.getList()) {
                            isLastPage = dataOfProductList.isIsLastPage();//jsonObjectData.getBoolean("isLastPage");
                            List<DataOfProductList.ProductInfoBean> pjsonListObject = dataOfProductList.getList();//gson.fromJson(jsonObjectData.optString("list"), new TypeToken<List<ProductInfoBean>>(){}.getType());
                            if (null != pjsonListObject && pjsonListObject.size() > 0) {
                                if (null != mProjectBeans && mProjectBeans.size() == 0) {
                                    DataOfProductList.ProductInfoBean bean = new DataOfProductList.ProductInfoBean();
                                    bean.setFirstProject(true);
                                    mProjectBeans.add(bean);
                                }
                                mProjectBeans.addAll(pjsonListObject);
                                isLastPage = dataOfProductList.getTotal() <= mProjectBeans.size();
                                productInfoBeanCommonAdapter.notifyDataSetChanged();
                                //插入数据库
                                getProjectDaoUtil();
                                setListProjectOfDao(pjsonListObject);
                                projectDaoUtil.insertListProject(projectList);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    listViewCustom.finishRefresh();
                    listViewCustom.finishLoadMore();
                }
            }

            @Override
            public void onFailure(Call call, Exception e) {
                if (mPageNum == 0) {
                    listViewCustom.finishRefresh(false);
                }
                if (mPageNum > 0) {
                    listViewCustom.finishLoadMore(false);
                }
                if (mProjectBeans != null && mProjectBeans.size() == 0) {
                    loadDataFromDB();
                }
            }
        });
    }

    /**
     * 搜索数据库数据
     */
    private void searchDataFromDB() {
        if (projectDaoUtil == null) {
            getProjectDaoUtil();
        }
        String sql = "where NAME = ?";
        setFromDB(convertProject2ProductInfoBean(projectDaoUtil.queryProjectBySql(sql, new String[]{mSearchString})));
    }

    /**
     * 加载数据库数据
     */
    private void loadDataFromDB() {
        if (projectDaoUtil == null) {
            getProjectDaoUtil();
        }
        setFromDB(convertProject2ProductInfoBean(projectDaoUtil.queryAllProject()));
    }

    private void setFromDB(List<DataOfProductList.ProductInfoBean> pjsonListObject) {
        mProjectBeans.clear();
        DataOfProductList.ProductInfoBean bean = new DataOfProductList.ProductInfoBean();
        bean.setFirstProject(true);
        mProjectBeans.add(bean);
        if (null != pjsonListObject && pjsonListObject.size() > 0) {
            mProjectBeans.addAll(pjsonListObject);
        }
        isLastPage = false;
        productInfoBeanCommonAdapter.notifyDataSetChanged();
        listViewCustom.finishRefresh();
    }

    private void uploadAll(DataOfProductList.ProductInfoBean productInfoBean) {
        if (!EasyPermissions.hasPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            EasyPermissions.requestPermissions(this, "上传文件需要用户读写文件的权限", 100, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            return;
        }
        ProjectDaoUtil projectDaoUtil = new ProjectDaoUtil(this);
        Project project = projectDaoUtil.queryProjectById(productInfoBean.getId());
        upAnswerToService(productInfoBean.getId() + "", productInfoBean.getEditor());//包括了上传证据文件的接口
        upEditProjectToService(project);
    }

    //上传评级信息
    private void upAnswerToService(final String productionid, String editor) {
        List<Answer> answerList = answerDaoUtil.queryElmentsByQueryBuilder(productionid);
        if (answerList == null || answerList.isEmpty()) {
            ToastUtil.showLongToast(this, "答案为空，请填写答案");
            return;
        }

        List<String> paths = new ArrayList<>();
        JSONObject jsonObject = new JSONObject();
        mProgressBar.setVisibility(View.VISIBLE);
        try {
            jsonObject.put("projectId", productionid);
            jsonObject.put("editor", editor);
            JSONArray questionList = new JSONArray();
            for (Answer answer : answerList) {
                if (answer.getUpload() == 0) {
                    // 未上传
                    paths.add(answer.getZhengjuPath());
                    JSONObject question = new JSONObject();
                    question.put("answerDividingValue", answer.getAnswerDividingValue());
                    question.put("answerOptionIds", answer.getAnswerOptionIds());
                    question.put("id", answer.getId());
                    question.put("remark", answer.getRemark());
                    question.put("yn", answer.getYn());
                    question.put("editor", answer.getEditor());
                    questionList.put(question);
                }
            }
            jsonObject.put("questionList", questionList);
            upEvidenceToService(paths);//上传证据文件
            OkhttpUtil.okHttpPostJson(config.URL + config.AnswerQuestion_Url, jsonObject.toString(), config.getHeaderMap(), new CallBackUtil.CallBackString() {
                @Override
                public void onFailure(Call call, Exception e) {
                    mProgressBar.setVisibility(View.GONE);
                    ToastUtil.showLongToast(ProjectListActivity.this, "上传答案失败");
                }

                @Override
                public void onResponse(String response) {
                    ResponseBean responseBean = gson.fromJson(response, ResponseBean.class);
                    if (responseBean != null && responseBean.getStatusCode().equals("200")) {
                        ToastUtil.showLongToast(ProjectListActivity.this, "答案上传成功");
                        //更新本地数据
                        upLocalData(productionid);
                        answerDaoUtil.deleteAll();
                    } else {
                        onFailure(null, null);
                    }

                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
            mProgressBar.setVisibility(View.GONE);
        }

    }

    /**
     * 更新本地数据
     */
    private void upLocalData(String productionid) {
        downloadRatingInfo(productionid,false);
    }


    //上传证据接口

    private void upEvidenceToService(List<String> filePaths) {
        if (filePaths == null || filePaths.isEmpty()) {
            return;
        }
        List<File> files = new ArrayList<>();
        for (String path : filePaths) {
            if (TextUtils.isEmpty(path)) {
                continue;
            }
            if (path.contains(",")) {
                String[] split = path.split(",");
                if (null != split && split.length > 0) {
                    for (String filePath : split) {
                        File file = new File(filePath);
                        if (file.isFile()) {
                            files.add(file);
                        }
                    }
                } else {
                    continue;
                }
            } else {
                File file = new File(path);
                if (file.isFile()) {
                    files.add(file);
                }
            }
        }
        if (files.isEmpty()) {
            return;
        }
        OkhttpUtil.okHttpUploadListFile(config.URL + config.Evidence_Submit_Url, null, files, "file", "file", config.getHeaderMap(), new CallBackUtil.CallBackString() {

            @Override
            public void onFailure(Call call, Exception e) {
                ToastUtil.showLongToast(ProjectListActivity.this, "上传证据失败");
            }

            @Override
            public void onResponse(String response) {
                ResponseBean responseBean = gson.fromJson(response, ResponseBean.class);
                if (responseBean != null && responseBean.getStatusCode().equals("200")) {
                    ToastUtil.showLongToast(ProjectListActivity.this, "上传证据成功");
                } else {
                    onFailure(null, null);
                }

            }
        });
    }

    //上传项目接口
    private void upEditProjectToService(Project productInfoBean) {
        try {
            JSONObject params = new JSONObject();

            JSONObject jsonProject = new JSONObject();
            jsonProject.put("id", productInfoBean.getId());
            jsonProject.put("name", productInfoBean.getName());
            jsonProject.put("propertyScope", productInfoBean.getPropertyScope());
            jsonProject.put("remark", productInfoBean.getRemark());
            jsonProject.put("secondUnit", productInfoBean.getSecondUnit());
            jsonProject.put("unitName", productInfoBean.getUnitName());
            jsonProject.put("status", productInfoBean.getStatus());
//            jsonProject.put("templateId", productInfoBean.getTemplateId());
            params.put("tbProject", jsonProject);

            List<ProjectUsersBean> projectUsersBeans = projectUserDaoUtil.queryProjectByQueryBuilder(productInfoBean.getId());
            JSONArray jsonInterviewees = new JSONArray();
            if (projectUsersBeans != null && !projectUsersBeans.isEmpty()) {
                for (ProjectUsersBean interviewee : projectUsersBeans) {
                    JSONObject object = new JSONObject();
                    object.put("addressOrPosition", interviewee.getAddressOrPosition());
                    object.put("email", interviewee.getEmail());
                    object.put("name", interviewee.getName());
                    object.put("phone", interviewee.getPhone());
                    object.put("type", interviewee.getType());
                    jsonInterviewees.put(object);
                }
            }
            params.put("projectUsersList", jsonInterviewees);

            OkhttpUtil.okHttpPostJson(config.URL + config.Edit_Project_Url, params.toString(), config.getHeaderMap(), new CallBackUtil.CallBackString() {
                @Override
                public void onFailure(Call call, Exception e) {
                    ToastUtil.showLongToast(ProjectListActivity.this, "项目修改失败");
                }

                @Override
                public void onResponse(String response) {
                    ResponseBean responseBean = gson.fromJson(response, ResponseBean.class);
                    if (responseBean != null && responseBean.getStatusCode().equals("200")) {
                        ToastUtil.showLongToast(ProjectListActivity.this, "项目修改成功");
                    } else {
                        onFailure(null, null);
                    }

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void getProjectDaoUtil() {
        projectDaoUtil = new ProjectDaoUtil(this);
    }

    // 待入库项目列表
    private List<Project> projectList;

    /**
     * 组装项目列表入库数据
     *
     * @param pjsonListObject
     */
    private void setListProjectOfDao(List<DataOfProductList.ProductInfoBean> pjsonListObject) {
        if (projectList == null) {
            projectList = new ArrayList<Project>();
        }
        projectList.clear();

        for (DataOfProductList.ProductInfoBean productInfoBean : pjsonListObject) {
            Project project = new Project();
            project.setAuditLeaderAddress((String) productInfoBean.getAuditLeaderAddress());
            project.setAuditLeaderEmail((String) productInfoBean.getAuditLeaderEmail());
            project.setAuditLeaderName(productInfoBean.getAuditLeaderName());
            project.setAuditLeaderPhone((String) productInfoBean.getAuditLeaderPhone());
            project.setCreateTime(productInfoBean.getCreateTime());
            project.setCreator(productInfoBean.getCreator());
            project.setEditor(productInfoBean.getEditor());
            project.setEditTime(productInfoBean.getEditTime());
            project.setId(Long.valueOf(productInfoBean.getId()));
            project.setName(productInfoBean.getName());
            project.setPropertyScope(productInfoBean.getPropertyScope());
            project.setRemark(productInfoBean.getRemark());
            project.setSecondUnit(productInfoBean.getSecondUnit());
            project.setStatus(productInfoBean.getStatus());
            project.setTemplateId(productInfoBean.getTemplateId());
            project.setYn(productInfoBean.getYn());
            project.setUnitName(productInfoBean.getUnitName());
            project.setTopicIds(productInfoBean.getTopicIds());
            projectList.add(project);

        }

    }

    private List<DataOfProductList.ProductInfoBean> convertProject2ProductInfoBean(List<Project> projects) {
        if (projects == null || projects.isEmpty()) {
            return null;
        }

        List<DataOfProductList.ProductInfoBean> productInfoBeans = new ArrayList<>();
        for (Project project : projects) {
            DataOfProductList.ProductInfoBean productInfoBean = new DataOfProductList.ProductInfoBean();
            productInfoBean.setAuditLeaderAddress(project.getAuditLeaderAddress());
            productInfoBean.setAuditLeaderEmail(project.getAuditLeaderEmail());
            productInfoBean.setAuditLeaderName(project.getAuditLeaderName());
            productInfoBean.setAuditLeaderPhone(project.getAuditLeaderPhone());
            productInfoBean.setCreateTime(project.getCreateTime());
            productInfoBean.setCreator(project.getCreator());
            productInfoBean.setEditor(project.getEditor());
            productInfoBean.setEditTime(project.getEditTime());
            productInfoBean.setId(project.getId().intValue());
            productInfoBean.setName(project.getName());
            productInfoBean.setPropertyScope(project.getPropertyScope());
            productInfoBean.setRemark(project.getRemark());
            productInfoBean.setSecondUnit(project.getSecondUnit());
            productInfoBean.setStatus(project.getStatus());
            productInfoBean.setTemplateId(project.getTemplateId());
            productInfoBean.setYn(project.getYn());
            productInfoBean.setUnitName(project.getUnitName());
            productInfoBean.setTopicIds(project.getTopicIds());
            productInfoBeans.add(productInfoBean);
        }
        return productInfoBeans;
    }

    private List<Elements> elementsList;
    private List<Topics> topicsList;
    private List<ProjectUsersBean> projectUserList;

    /**
     * 组装项目评级入库信息
     */
    private void setProductRatingInfoOfDao(String productinfo_id, JSONArray projectUsersJsonArray, JSONArray _elementsJsonArry, JSONArray _topicsJsonArray, Gson gson) throws JSONException {

        if (projectUserList == null) {
            projectUserList = new ArrayList<>();
        }
        projectUserList.clear();
        for (int i = 0; i < projectUsersJsonArray.length(); i++) {
            JSONObject userObj = (JSONObject) projectUsersJsonArray.get(i);
            ProjectUsersBean elements = gson.fromJson(userObj.toString(), ProjectUsersBean.class);
            elements.projectId = Long.valueOf(productinfo_id);
            projectUserList.add(elements);
        }

        if (elementsList == null) {
            elementsList = new ArrayList<Elements>();
        }
        elementsList.clear();
        for (int i = 0; i < _elementsJsonArry.length(); i++) {
            JSONObject elmentsJson = (JSONObject) _elementsJsonArry.get(i);
            Elements elements = gson.fromJson(elmentsJson.toString(), Elements.class);
            elements.setProductinfo_id(productinfo_id);
            elementsList.add(elements);
        }

        if (topicsList == null) {
            topicsList = new ArrayList<Topics>();
        }
        topicsList.clear();
        for (int i = 0; i < _topicsJsonArray.length(); i++) {
            JSONObject topicJson = (JSONObject) _topicsJsonArray.get(i);
            Topics topics = gson.fromJson(topicJson.toString(), Topics.class);
            topics.setProductId(productinfo_id);
            topicsList.add(topics);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        ToastUtil.showLongToast(this, "授权成功，请重试！");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        ToastUtil.showLongToast(this, "需要读取文件的权限，用户授权失败！");
    }
}
